import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:system_tray/system_tray.dart';
import 'package:window_manager/window_manager.dart';
import 'dart:io' show Platform;
import 'package:flutter/services.dart';
import 'package:video_player_win/video_player_win_plugin.dart';
import 'services/music_player_service.dart';
import 'services/system_tray_service.dart';
import 'screens/home_screen.dart';
import 'core/auth_store.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 为 Windows 平台注册 video_player 的 Media Foundation 实现
  if (Platform.isWindows) {
    WindowsVideoPlayer.registerWith();
  }
  
  // 初始化窗口管理器
  if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
    await windowManager.ensureInitialized();
    
    WindowOptions windowOptions = const WindowOptions(
      size: Size(1080, 700),
      center: true,
      backgroundColor: Colors.transparent,
      skipTaskbar: false,
      titleBarStyle: TitleBarStyle.normal,
    );
    
    windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();
      await windowManager.setPreventClose(true);
    });
  }
  
  runApp(const LyMusicApp());
}

class LyMusicApp extends StatefulWidget {
  const LyMusicApp({super.key});

  @override
  State<LyMusicApp> createState() => _LyMusicAppState();
}

class _LyMusicAppState extends State<LyMusicApp> with WindowListener {
  late MusicPlayerService _musicPlayerService;
  late final AuthStore _authStore;
  static const MethodChannel _mediaControlsChannel = MethodChannel('com.example.ly_music/media_controls');

  @override
  void initState() {
    super.initState();
    _musicPlayerService = MusicPlayerService();
    _authStore = AuthStore();
    _authStore.load();
    _initializeSystemTray();
    windowManager.addListener(this);

    // 处理来自原生的媒体按键（方向盘、耳机）回调
    _mediaControlsChannel.setMethodCallHandler((call) async {
      switch (call.method) {
        case 'skipToNext':
          await _musicPlayerService.next();
          break;
        case 'skipToPrevious':
          await _musicPlayerService.previous();
          break;
        case 'play':
          await _musicPlayerService.resume();
          break;
        case 'pause':
          await _musicPlayerService.pause();
          break;
        case 'togglePlayPause':
          await _musicPlayerService.togglePlayPause();
          break;
        case 'seekTo':
          final args = call.arguments as Map<dynamic, dynamic>?;
          final pos = args?['position'] as int?;
          if (pos != null) {
            await _musicPlayerService.seekToImmediate(Duration(milliseconds: pos));
          }
          break;
      }
    });

    // 监听播放器状态，主动同步到原生的MediaSession
    _musicPlayerService.addListener(_syncPlaybackStateToNative);
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    SystemTrayService.dispose();
    _musicPlayerService.removeListener(_syncPlaybackStateToNative);
    super.dispose();
  }

  Future<void> _initializeSystemTray() async {
    if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
      await SystemTrayService.initialize(_musicPlayerService);
    }
  }

  @override
  void onWindowClose() async {
    bool isPreventClose = await windowManager.isPreventClose();
    if (isPreventClose) {
      await windowManager.hide();
    }
  }

  void _syncPlaybackStateToNative() {
    // 只在 Android 平台上同步播放状态到原生媒体控制
    if (Platform.isAndroid) {
      final isPlaying = _musicPlayerService.isPlaying;
      final positionMs = _musicPlayerService.position.inMilliseconds;
      _mediaControlsChannel.invokeMethod('updatePlaybackState', {
        'isPlaying': isPlaying,
        'position': positionMs,
      });
      final song = _musicPlayerService.currentSong;
      if (song != null) {
        _mediaControlsChannel.invokeMethod('updateNowPlaying', {
          'title': song.name,
          'artist': song.artistsString,
          'durationMs': _musicPlayerService.duration.inMilliseconds,
          'artUri': song.albumImageUrl,
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: _musicPlayerService),
        ChangeNotifierProvider.value(value: _authStore),
      ],
      child: MaterialApp(
        title: '洛页云音乐',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          colorScheme: const ColorScheme.light(
            primary: Color.fromARGB(255, 99, 137, 241), // 现代青色
            secondary: Color.fromARGB(255, 212, 192, 6), // 渐变黄色
            tertiary: Color(0xFF06B6D4), // 青色点缀
            surface: Color(0xFFFAFAFA), // 浅灰背景
            surfaceContainer: Color(0xFFFFFFFF), // 白色容器
            surfaceContainerHighest: Color(0xFFF1F5F9), // 高层级容器
            onPrimary: Colors.white,
            onSecondary: Colors.white,
            onSurface: Color(0xFF1E293B), // 深色文字
            onSurfaceVariant: Color(0xFF64748B), // 次要文字
            outline: Color(0xFFE2E8F0), // 边框色
          ),
          useMaterial3: true,
          // 统一字体主题
          textTheme: const TextTheme(
            // 大标题
            headlineLarge: TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.5,
            ),
            headlineMedium: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.25,
            ),
            headlineSmall: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w600,
            ),
            // 标题
            titleLarge: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
            titleMedium: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
            titleSmall: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
            ),
            // 正文
            bodyLarge: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w400,
              letterSpacing: 0.0,
            ),
            bodyMedium: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w400,
              letterSpacing: 0.0,
            ),
            bodySmall: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w400,
              letterSpacing: 0.0,
            ),
            // 标签
            labelLarge: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              letterSpacing: 0.0,
            ),
            labelMedium: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              letterSpacing: 0.0,
            ),
            labelSmall: TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w500,
              letterSpacing: 0.0,
            ),
          ),
          appBarTheme: const AppBarTheme(
            centerTitle: true,
            elevation: 0,
            backgroundColor: Color(0xFFFAFAFA),
            foregroundColor: Color(0xFF1E293B),
          ),
          cardTheme: CardThemeData(
            elevation: 2,
            shadowColor: Colors.black.withOpacity(0.1),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
          ),
          elevatedButtonTheme: ElevatedButtonThemeData(
            style: ElevatedButton.styleFrom(
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
          ),
        ),
        darkTheme: ThemeData(
          colorScheme: const ColorScheme.dark(
            primary: Color(0xFF8B5CF6), // 亮紫色
            secondary: Color(0xFFA855F7), // 渐变紫色
            tertiary: Color(0xFF22D3EE), // 亮青色
            surface: Color(0xFF0F172A), // 深色背景
            surfaceContainer: Color(0xFF1E293B), // 深色容器
            surfaceContainerHighest: Color(0xFF334155), // 高层级容器
            onPrimary: Colors.white,
            onSecondary: Colors.white,
            onSurface: Color(0xFFF1F5F9), // 浅色文字
            onSurfaceVariant: Color(0xFF94A3B8), // 次要文字
            outline: Color(0xFF475569), // 边框色
          ),
          useMaterial3: true,
          // 统一字体主题
          textTheme: const TextTheme(
            // 大标题
            headlineLarge: TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.5,
            ),
            headlineMedium: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.25,
            ),
            headlineSmall: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w600,
            ),
            // 标题
            titleLarge: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
            titleMedium: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
            titleSmall: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
            ),
            // 正文
             bodyLarge: TextStyle(
               fontSize: 16,
               fontWeight: FontWeight.w400,
               letterSpacing: 0.0,
             ),
             bodyMedium: TextStyle(
               fontSize: 14,
               fontWeight: FontWeight.w400,
               letterSpacing: 0.0,
             ),
             bodySmall: TextStyle(
               fontSize: 12,
               fontWeight: FontWeight.w400,
               letterSpacing: 0.0,
             ),
            // 标签
             labelLarge: TextStyle(
               fontSize: 14,
               fontWeight: FontWeight.w500,
               letterSpacing: 0.0,
             ),
             labelMedium: TextStyle(
               fontSize: 12,
               fontWeight: FontWeight.w500,
               letterSpacing: 0.0,
             ),
             labelSmall: TextStyle(
               fontSize: 10,
               fontWeight: FontWeight.w500,
               letterSpacing: 0.0,
             ),
          ),
          appBarTheme: const AppBarTheme(
            centerTitle: true,
            elevation: 0,
            backgroundColor: Color(0xFF0F172A),
            foregroundColor: Color(0xFFF8FAFC),
          ),
          cardTheme: CardThemeData(
            elevation: 4,
            shadowColor: Colors.black.withOpacity(0.3),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
          ),
          elevatedButtonTheme: ElevatedButtonThemeData(
            style: ElevatedButton.styleFrom(
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
          ),
        ),
        home: const HomeScreen(),
      ),
    );
  }
}
